#!/bin/bash
# worker 节点操作

# 检查 centos / hostname
echo 修改 hostname
hostnamectl set-hostname work$1
# 查看修改结果
hostnamectl status
# 设置 hostname 解析
echo "127.0.0.1   $(hostname)" >> /etc/hosts


# 安装containerd/kubelet/kubeadm/kubectl

# 阿里云 docker hub 镜像
export REGISTRY_MIRROR=https://registry.cn-hangzhou.aliyuncs.com

echo 安装 docker
# https://docs.docker.com/engine/install/centos/

yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
yum install -y yum-utils
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# --allowerasing：可能一些依赖包冲突，需要覆盖安装
yum install -y --allowerasing docker-ce docker-ce-cli containerd.io

docker --version
echo 配置 Docker 守护程序，尤其是使用 systemd 来管理容器的cgroup
# https://kubernetes.io/zh/docs/setup/production-environment/container-runtimes/#docker
mkdir /etc/docker
cat <<EOF | sudo tee /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF
# 如果启动过重启
systemctl enable docker
systemctl daemon-reload
systemctl start docker

# 创建 docker 用户组并添加用户到该用户组，然后该用户在运行 docker 命令时不再需要 sudo
# https://docs.docker.com/engine/install/linux-postinstall/

# groupadd docker
# usermod -aG docker $USER
# newgrp docker

echo 安装 nfs-utils
# 必须先安装 nfs-utils 才能挂载 nfs 网络存储
yum install -y nfs-utils
yum install -y wget

echo 关闭 防火墙
systemctl stop firewalld
systemctl disable firewalld

echo 关闭 SeLinux
setenforce 0
sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config

echo 关闭 swap
swapoff -a
yes | cp /etc/fstab /etc/fstab_bak
cat /etc/fstab_bak |grep -v swap > /etc/fstab

echo 配置K8S的yum源
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
       http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

# 卸载旧版本
yum remove -y kubelet kubeadm kubectl

# 安装kubelet、kubeadm、kubectl
# 将 ${1} 替换为 kubernetes 版本号，例如 1.20.1
yum install -y kubelet-1.20.1 kubeadm-1.20.1 kubectl-1.20.1

# crictl config runtime-endpoint /run/containerd/containerd.sock

echo 重启 docker，并启动 kubelet
systemctl daemon-reload
systemctl enable kubelet && systemctl start kubelet

kubelet --version


echo 初始化 worker节点

# 初始化worker
# 针对所有的 worker 节点执行
# 只在 worker 节点执行
# 替换 x.x.x.x 为 master 节点的内网 IP
export MASTER_IP=10.0.5.107
# 替换 apiserver.demo 为初始化 master 节点时所使用的 APISERVER_NAME
export APISERVER_NAME=k8s.weipu
echo "${MASTER_IP}  ${APISERVER_NAME}" >> /etc/hosts

echo "初始化 worker 并在 master 给 worker 打标签"